package se.grp03.fmtunerapp.adapters;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class UdpAdapter implements IOInterface{

	private static final int UDP_PORT = 1025;
	private static final String SERVER_IP = "";
	private Socket scheduler_socket;
	private Socket socket;
	private BufferedWriter out_stream_writer;
	private BufferedReader in_stream_reader;
	private String msg;
	
	public UdpAdapter(String msg){
		
		this.msg = msg;
	}
	
	@Override
	public void doOpen() {
		
		try {
			
			scheduler_socket = new Socket(SERVER_IP, UDP_PORT);
			out_stream_writer =  new BufferedWriter( new OutputStreamWriter(scheduler_socket.getOutputStream()));
			in_stream_reader = new BufferedReader( new InputStreamReader(scheduler_socket.getInputStream()));
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Returns a message read from a server or null if not message was read
	 */
	@Override
	public String doRead() {
		
		String msg = null;
		try {
			String line = "";
			
			while( ( line =  in_stream_reader.readLine()) != null )
				msg+= line;
						
		} catch (IOException e) {
			
			e.printStackTrace();
		}		
		
		return msg;
	}

	@Override
	public void doWrite() {
		
		try {
			out_stream_writer.write(msg);
		} catch (IOException e) {
			
			e.printStackTrace();
		}		
	}

	@Override
	public void doClose() {
		
		try {
			
			if( socket.isConnected() )
				socket.close();
			
			out_stream_writer = null;
			in_stream_reader = null;
			
			scheduler_socket.close();
			scheduler_socket = null;
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}